Ext.namespace("Microtraining.Admin.Member");
Mt = Microtraining.Admin;
Mt.Member={
	/**
	 * 全局配置
	 */
	Config:{
		/**
		 *分页:每页显示记录数
		 */
		PageSize:15,
		/**
		 *显示配置
		 */
		View:{
			/**
			 * 显示会员的视图相对会员列表Grid的位置
			 * 1:上方,2:下方,3:左侧,4:右侧,
			 */
			Direction:2,
			/**
			 *是否显示。
			 */
			IsShow:0,
			/**
			 * 是否固定显示会员信息页(或者打开新窗口)
			 */
			IsFix:0
		}
	},
	/**
	 * Cookie设置
	 */
	Cookie:new Ext.state.CookieProvider(),
	/**
	 * 初始化
	 */
	Init:function(){
		if (Mt.Member.Cookie.get('View.Direction')){
			Mt.Member.Config.View.Direction=Mt.Member.Cookie.get('View.Direction');
		}
		if (Mt.Member.Cookie.get('View.IsFix')!=null){
			Mt.Member.Config.View.IsFix=Mt.Member.Cookie.get('View.IsFix');
		}
	}
};
/**
 * Model:数据模型
 */
Mt.Member.Store = {
	/**
	 * 会员
	 */
	memberStore:new Ext.data.Store({
		reader: new Ext.data.JsonReader({
			totalProperty: 'totalCount',
			successProperty: 'success',
			root: 'data',remoteSort: true,
			fields : [
           {name: 'member_id',type: 'int'},
           {name: 'company_id',type: 'int'},
           {name: 'company_name',type: 'string'},
           {name: 'department_id',type: 'int'},
           {name: 'department_name',type: 'string'},
           {name: 'position_id',type: 'int'},
           {name: 'position_name',type: 'string'},
           {name: 'area_id',type: 'int'},
           {name: 'area_name',type: 'string'},
           {name: 'username',type: 'string'},
           {name: 'password',type: 'string'},
           {name: 'realname',type: 'string'},
           {name: 'code',type: 'string'},
           {name: 'tel',type: 'string'},
           {name: 'email',type: 'string'},
           {name: 'qq',type: 'string'},
           {name: 'weixin',type: 'string'},
           {name: 'icon_image',type: 'string'},
           {name: 'point',type: 'float'}
			]}
		),
		writer: new Ext.data.JsonWriter({
			encode: false
		}),
		listeners : {
			beforeload : function(store, options) {
				if (Ext.isReady) {
					if (!options.params.limit)options.params.limit=Mt.Member.Config.PageSize;
					Ext.apply(options.params, Mt.Member.View.Running.memberGrid.filter);//保证分页也将查询条件带上
				}
			}
		}
	}),
   /**
    * 企业
    */
   companyStoreForCombo:new Ext.data.Store({
      proxy: new Ext.data.HttpProxy({
        url: 'home/admin/src/httpdata/company.php'
      }),
      reader: new Ext.data.JsonReader({
        root: 'companys',
        autoLoad: true,
        totalProperty: 'totalCount',
        idProperty: 'company_id'
      }, [
        {name: 'company_id', mapping: 'company_id'},
        {name: 'company_name', mapping: 'company_name'}
      ])
   }),
   /**
    * 部门
    */
   departmentStoreForCombo:new Ext.data.Store({
      proxy: new Ext.data.HttpProxy({
        url: 'home/admin/src/httpdata/department.php'
      }),
      reader: new Ext.data.JsonReader({
        root: 'departments',
        autoLoad: true,
        totalProperty: 'totalCount',
        idProperty: 'department_id'
      }, [
        {name: 'department_id', mapping: 'department_id'},
        {name: 'department_name', mapping: 'department_name'}
      ])
   }),
   /**
    * 职位
    */
   positionStoreForCombo:new Ext.data.Store({
      proxy: new Ext.data.HttpProxy({
        url: 'home/admin/src/httpdata/position.php'
      }),
      reader: new Ext.data.JsonReader({
        root: 'positions',
        autoLoad: true,
        totalProperty: 'totalCount',
        idProperty: 'position_id'
      }, [
        {name: 'position_id', mapping: 'position_id'},
        {name: 'position_name', mapping: 'position_name'}
      ])
   }),
   /**
    * 地区
    */
   areaStoreForCombo:new Ext.data.Store({
      proxy: new Ext.data.HttpProxy({
        url: 'home/admin/src/httpdata/area.php'
      }),
      reader: new Ext.data.JsonReader({
        root: 'areas',
        autoLoad: true,
        totalProperty: 'totalCount',
        idProperty: 'area_id'
      }, [
        {name: 'area_id', mapping: 'area_id'},
        {name: 'area_name', mapping: 'area_name'}
      ])
   })
};
/**
 * View:会员显示组件
 */
Mt.Member.View={
	/**
	 * 编辑窗口：新建或者修改会员
	 */
	EditWindow:Ext.extend(Ext.Window,{
		constructor : function(config) {
			config = Ext.apply({
				/**
				 * 自定义类型:保存类型
				 * 0:保存窗口,1:修改窗口
				 */
				savetype:0,
				closeAction : "hide",
				constrainHeader:true,maximizable: true,collapsible: true,
				width : 450,height : 550,minWidth : 400,minHeight : 450,
				layout : 'fit',plain : true,buttonAlign : 'center',
				defaults : {
					autoScroll : true
				},
				listeners:{
					beforehide:function(){
						this.editForm.form.getEl().dom.reset();
					}
				},
				items : [
					new Ext.form.FormPanel({
						ref:'editForm',layout:'form',fileUpload: true,
						labelWidth : 100,labelAlign : "center",
						bodyStyle : 'padding:5px 5px 0',align : "center",
						api : {},
						defaults : {
							xtype : 'textfield',anchor:'98%'
						},
						items : [
                   {xtype: 'hidden',name : 'member_id',ref:'../member_id'},
                   {xtype: 'hidden',name : 'department_id',ref:'../department_id'},
                   {
                      fieldLabel : '部门(<font color=red>*</font>)',xtype: 'combo',name : 'department_name',ref : '../department_name',allowBlank:false,
                      store:Mt.Member.Store.departmentStoreForCombo,emptyText: '请选择部门',itemSelector: 'div.search-item',
                      loadingText: '查询中...',width: 570, pageSize:Mt.Member.Config.PageSize,
                      displayField:'department_name',grid:this,
                      mode: 'remote',  editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                      forceSelection: true,triggerAction: 'all',resizable:false,selectOnFocus:true,
                      tpl:new Ext.XTemplate(
                         '<tpl for="."><div class="search-item">',
                            '<h3>{department_name}</h3>',
                         '</div></tpl>'
                      ),
                      listeners:{
                         'beforequery': function(event){delete event.combo.lastQuery;}
                      },
                      onSelect:function(record,index){
                         if(this.fireEvent('beforeselect', this, record, index) !== false){
                           this.grid.department_id.setValue(record.data.department_id);
                           this.grid.department_name.setValue(record.data.department_name);
                           this.collapse();
                         }
                      }
                   },
                   {xtype: 'hidden',name : 'position_id',ref:'../position_id'},
                   {
                      fieldLabel : '职位(<font color=red>*</font>)',xtype: 'combo',name : 'position_name',ref : '../position_name',allowBlank:false,
                      store:Mt.Member.Store.positionStoreForCombo,emptyText: '请选择职位',itemSelector: 'div.search-item',
                      loadingText: '查询中...',width: 570, pageSize:Mt.Member.Config.PageSize,
                      displayField:'position_name',grid:this,
                      mode: 'remote',  editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                      forceSelection: true,triggerAction: 'all',resizable:false,selectOnFocus:true,
                      tpl:new Ext.XTemplate(
                         '<tpl for="."><div class="search-item">',
                            '<h3>{position_name}</h3>',
                         '</div></tpl>'
                      ),
                      listeners:{
                         'beforequery': function(event){delete event.combo.lastQuery;}
                      },
                      onSelect:function(record,index){
                         if(this.fireEvent('beforeselect', this, record, index) !== false){
                           this.grid.position_id.setValue(record.data.position_id);
                           this.grid.position_name.setValue(record.data.position_name);
                           this.collapse();
                         }
                      }
                   },
                   {xtype: 'hidden',name : 'area_id',ref:'../area_id'},
                   {
                      fieldLabel : '地区(<font color=red>*</font>)',xtype: 'combo',name : 'area_name',ref : '../area_name',allowBlank:false,
                      store:Mt.Member.Store.areaStoreForCombo,emptyText: '请选择地区',itemSelector: 'div.search-item',
                      loadingText: '查询中...',width: 570, pageSize:Mt.Member.Config.PageSize,
                      displayField:'area_name',grid:this,
                      mode: 'remote',  editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                      forceSelection: true,triggerAction: 'all',resizable:false,selectOnFocus:true,
                      tpl:new Ext.XTemplate(
                         '<tpl for="."><div class="search-item">',
                            '<h3>{area_name}</h3>',
                         '</div></tpl>'
                      ),
                      listeners:{
                         'beforequery': function(event){delete event.combo.lastQuery;}
                      },
                      onSelect:function(record,index){
                         if(this.fireEvent('beforeselect', this, record, index) !== false){
                           this.grid.area_id.setValue(record.data.area_id);
                           this.grid.area_name.setValue(record.data.area_name);
                           this.collapse();
                         }
                      }
                   },
                   {fieldLabel : '用户名(<font color=red>*</font>)',name : 'username',allowBlank:false},
                   {fieldLabel : '密码(<font color=red>*</font>)',name : 'password',inputType:'password',ref:'../password'},
                   {xtype: 'hidden',name : 'password_old',ref:'../password_old'},
                   {fieldLabel : '姓名(<font color=red>*</font>)',name : 'realname',allowBlank:false},
                   {fieldLabel : '员工号',name : 'code'},
                   {fieldLabel : '电话(<font color=red>*</font>)',name : 'tel',allowBlank:false},
                   {fieldLabel : 'email',name : 'email',vtype:'email'},
                   {fieldLabel : 'qq',name : 'qq'},
                   {fieldLabel : '微信',name : 'weixin'},
                   {xtype: 'hidden',  name : 'icon_image',ref:'../icon_image'},
                   {fieldLabel : '头像',name : 'icon_imageUpload',ref:'../icon_imageUpload',xtype:'fileuploadfield',
                    emptyText: '请上传头像文件',buttonText: '',accept:'image/*',buttonCfg: {iconCls: 'upload-icon'}}
                    /*,
                   {xtype: 'hidden',name : 'point',ref:'../point'}*/
						]
					})
				],
				buttons : [{
					text: "",ref : "../saveBtn",scope:this,
					handler : function() {

						if (!this.editForm.getForm().isValid()) {
							return;
						}
						editWindow=this;
						if (this.savetype==0){
							this.editForm.api.submit=ExtServiceMember.save;
							this.editForm.getForm().submit({
								success : function(form, action) {
									Ext.Msg.alert("提示", "保存成功！");
									Mt.Member.View.Running.memberGrid.doSelectMember();
									form.reset();
									editWindow.hide();
								},
								failure : function(form, response) {
									Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
								}
							});
						}else{
							this.editForm.api.submit=ExtServiceMember.update;
							this.editForm.getForm().submit({
								success : function(form, action) {
									Mt.Member.View.Running.memberGrid.store.reload();
									Ext.Msg.show({title:'提示',msg: '修改成功！',buttons: {yes: '确定'},fn: function(){
										Mt.Member.View.Running.memberGrid.bottomToolbar.doRefresh();
									}});
									form.reset();
									editWindow.hide();
								},
								failure : function(form, response) {
									Ext.Msg.show({title:'提示',width:350,buttons: {yes: '确定'},msg:response.result.msg});
								}
							});
						}
					}
				}, {
					text : "取 消",scope:this,
					handler : function() {
						this.hide();
					}
				}, {
					text : "重 置",ref:'../resetBtn',scope:this,
					handler : function() {
						this.editForm.form.loadRecord(Mt.Member.View.Running.memberGrid.getSelectionModel().getSelected());
                this.icon_imageUpload.setValue(this.icon_image.getValue());

					}
				}]
			}, config);
			Mt.Member.View.EditWindow.superclass.constructor.call(this, config);
		}
	}),
	/**
	 * 显示会员详情
	 */
	MemberView:{
		/**
		 * Tab页：容器包含显示与会员所有相关的信息
		 */
		Tabs:Ext.extend(Ext.TabPanel,{
			constructor : function(config) {
				config = Ext.apply({
					region : 'south',collapseMode : 'mini',split : true,
					activeTab: 1, tabPosition:"bottom",resizeTabs : true,
					header:false,enableTabScroll : true,tabWidth:'auto', margins : '0 3 3 0',
					defaults : {
						autoScroll : true,
						layout:'fit'
					},
					listeners:{
						beforetabchange:function(tabs,newtab,currentTab){
							if (tabs.tabFix==newtab){
								if (Mt.Member.View.Running.memberGrid.getSelectionModel().getSelected()==null){
									Ext.Msg.alert('提示', '请先选择会员！');
									return false;
								}
								Mt.Member.Config.View.IsShow=1;
								Mt.Member.View.Running.memberGrid.showMember();
								Mt.Member.View.Running.memberGrid.tvpView.menu.mBind.setChecked(false);
								return false;
							}
						}
					},
					items: [
						{title:'+',tabTip:'取消固定',ref:'tabFix',iconCls:'icon-fix'}
					]
				}, config);
				Mt.Member.View.MemberView.Tabs.superclass.constructor.call(this, config);

				this.onAddItems();
			},
			/**
			 * 根据布局调整Tabs的宽度或者高度以及折叠
			 */
			enableCollapse:function(){
				if ((Mt.Member.Config.View.Direction==1)||(Mt.Member.Config.View.Direction==2)){
					this.width =Ext.getBody().getViewSize().width;
					this.height=Ext.getBody().getViewSize().height/2;
				}else{
					this.width =Ext.getBody().getViewSize().width/2;
					this.height=Ext.getBody().getViewSize().height;
				}
				this.ownerCt.setSize(this.width,this.height);
				if (this.ownerCt.collapsed)this.ownerCt.expand();
				this.ownerCt.collapsed=false;
			},
			onAddItems:function(){
				this.add(
					{title: '基本信息',ref:'tabMemberDetail',iconCls:'tabs',
					 tpl: [
						 '<table class="viewdoblock">',
                 '   <tr class="entry"><td class="head">公司</td><td class="content">{company_name}</td></tr>',
                 '   <tr class="entry"><td class="head">部门</td><td class="content">{department_name}</td></tr>',
                 '   <tr class="entry"><td class="head">职位</td><td class="content">{position_name}</td></tr>',
                 '   <tr class="entry"><td class="head">地区</td><td class="content">{area_name}</td></tr>',
                 '   <tr class="entry"><td class="head">用户名</td><td class="content">{username}</td></tr>',
                 '   <tr class="entry"><td class="head">姓名</td><td class="content">{realname}</td></tr>',
                 '   <tr class="entry"><td class="head">员工号</td><td class="content">{code}</td></tr>',
                 '   <tr class="entry"><td class="head">电话</td><td class="content">{tel}</td></tr>',
                 '   <tr class="entry"><td class="head">email</td><td class="content">{email}</td></tr>',
                 '   <tr class="entry"><td class="head">qq</td><td class="content">{qq}</td></tr>',
                 '   <tr class="entry"><td class="head">微信</td><td class="content">{weixin}</td></tr>',
                 '   <tr class="entry"><td class="head">头像路径</td><td class="content">{icon_image}</td></tr>',
                 '   <tr class="entry"><td class="head">头像</td><td class="content"><tpl if="icon_image"><a href="upload/images/{icon_image}" target="_blank"><img src="upload/images/{icon_image}" /></a></tpl></td></tr>',
                 '   <tr class="entry"><td class="head">积分</td><td class="content">{point}</td></tr>',
						 '</table>'
					 ]}
				);
           this.add(
              {title: '其他',iconCls:'tabs'}
           );
			}
		}),
		/**
		 * 窗口:显示会员信息
		 */
		Window:Ext.extend(Ext.Window,{
			constructor : function(config) {
				config = Ext.apply({
					title:"查看会员",constrainHeader:true,maximizable: true,minimizable : true,
					width : 705,height : 500,minWidth : 450,minHeight : 400,
					layout : 'fit',resizable:true,plain : true,bodyStyle : 'padding:5px;',
					closeAction : "hide",
					items:[new Mt.Member.View.MemberView.Tabs({ref:'winTabs',tabPosition:'top'})],
					listeners: {
						minimize:function(w){
							w.hide();
							Mt.Member.Config.View.IsShow=0;
							Mt.Member.View.Running.memberGrid.tvpView.menu.mBind.setChecked(true);
						},
						hide:function(w){
							Mt.Member.View.Running.memberGrid.tvpView.toggle(false);
						}
					},
					buttons: [{
						text: '新增会员',scope:this,
						handler : function() {this.hide();Mt.Member.View.Running.memberGrid.addMember();}
					},{
						text: '修改会员',scope:this,
						handler : function() {this.hide();Mt.Member.View.Running.memberGrid.updateMember();}
					}]
				}, config);
				Mt.Member.View.MemberView.Window.superclass.constructor.call(this, config);
			}
		})
	},
	/**
	 * 窗口：批量上传会员
	 */
	UploadWindow:Ext.extend(Ext.Window,{
		constructor : function(config) {
			config = Ext.apply({
				title : '批量上传会员数据',width : 400,height : 110,minWidth : 300,minHeight : 100,
				layout : 'fit',plain : true,bodyStyle : 'padding:5px;',buttonAlign : 'center',closeAction : "hide",
				items : [
					new Ext.form.FormPanel({
						ref:'uploadForm',fileUpload: true,
						width: 500,labelWidth: 50,autoHeight: true,baseCls: 'x-plain',
						frame:true,bodyStyle: 'padding: 10px 10px 10px 10px;',
						defaults: {
							anchor: '95%',allowBlank: false,msgTarget: 'side'
						},
						items : [{
							xtype : 'fileuploadfield',
							fieldLabel : '文 件',name : 'upload_file',ref:'upload_file',
							emptyText: '请上传会员Excel文件',buttonText: '',
							accept:'application/vnd.ms-excel',
							buttonCfg: {iconCls: 'upload-icon'}
						}]
					})
				],
				buttons : [{
						text : '上 传',
						scope:this,
						handler : function() {
							uploadWindow        =this;
							validationExpression  =/([\u4E00-\u9FA5]|\w)+(.xlsx|.XLSX|.xls|.XLS)$/;/**允许中文名*/
							var isValidExcelFormat = new RegExp(validationExpression);
							var result         = isValidExcelFormat.test(this.uploadForm.upload_file.getValue());
							if (!result){
								Ext.Msg.alert('提示', '请上传Excel文件，后缀名为xls或者xlsx！');
								return;
							}
							if (this.uploadForm.getForm().isValid()) {
								Ext.Msg.show({
									title : '请等待',msg : '文件正在上传中，请稍后...',
									animEl : 'loading',icon : Ext.Msg.WARNING,
									closable : true,progress : true,progressText : '',width : 300
								});
								this.uploadForm.getForm().submit({
									url : 'index.php?go=admin.upload.uploadMember',
									success : function(form, response) {
										Ext.Msg.alert('成功', '上传成功');
										uploadWindow.hide();
										uploadWindow.uploadForm.upload_file.setValue('');
										Mt.Member.View.Running.memberGrid.doSelectMember();
									},
									failure : function(form, response) {
										Ext.Msg.alert('错误', response.result.data);
									}
								});
							}
						}
					},{
						text : '取 消',
						scope:this,
						handler : function() {
							this.uploadForm.upload_file.setValue('');
							this.hide();
						}
					},{
            text : '下载模版',
            scope:this,
            handler : function() {
               ExtServiceMember.template('member',function(provider, response) {
                if (response.result) {
                  window.open(response.result);
                }
               });
            }
          }]
				}, config);
			Mt.Member.View.UploadWindow.superclass.constructor.call(this, config);
		}
	}),
	/**
	 * 窗口：批量上传商品图片
	 */
	BatchUploadImagesWindow:Ext.extend(Ext.Window,{
		constructor : function(config) {
			config = Ext.apply({
				width : 400,height : 180,minWidth : 300,minHeight : 100,closeAction : "hide",
				layout : 'fit',plain : true,bodyStYle : 'padding:5px;',buttonAlign : 'center',
				items : [
					new Ext.form.FormPanel({
						ref:'uploadForm',fileUpload: true,
						width: 500,labelWidth: 50,autoHeight: true,baseCls: 'x-plain',
						frame:true,bodyStyle: 'padding: 10px 10px 10px 10px;',
						defaults: {
							anchor: '95%',allowBlank: false,msgTarget: 'side'
						},
						items : [{
							xtype : 'fileuploadfield',fieldLabel : '文 件',ref:'upload_file',
							emptyText: '请批量上传更新时间文件(zip)',buttonText: '',
							accept:'application/zip,application/x-zip-compressed',
							buttonCfg: {iconCls: 'upload-icon'}
						},
						{xtype : 'displayfield',value:'*.图片名不能重名<br/>*.压缩文件最大不要超过50M'}]
					})
				],
				buttons : [{
						text : '上 传',
						scope:this,
						handler : function() {
							uploadImagesWindow    =this;
							validationExpression  =/([\u4E00-\u9FA5]|\w)+(.zip|.ZIP)$/;
							var isValidExcelFormat = new RegExp(validationExpression);
							var result         = isValidExcelFormat.test(this.uploadForm.upload_file.getValue());
							if (!result){
								Ext.Msg.alert('提示', '请上传ZIP文件，后缀名为zip！');
								return;
							}
							var uploadImageUrl='index.php?go=admin.upload.uploadMemberIcon_images';

							if (this.uploadForm.getForm().isValid()) {
								Ext.Msg.show({
									title : '请等待',msg : '文件正在上传中，请稍后...',
									animEl : 'loading',icon : Ext.Msg.WARNING,
									closable : true,progress : true,progressText : '',width : 300
								});
								this.uploadForm.getForm().submit({
									url : uploadImageUrl,
									success : function(form, response) {
										Ext.Msg.alert('成功', '上传成功');
										uploadImagesWindow.hide();
										uploadImagesWindow.uploadForm.upload_file.setValue('');
										Mt.Member.View.Running.memberGrid.doSelectMember();
									},
									failure : function(form, response) {
										if (response.result&&response.result.data){
											Ext.Msg.alert('错误', response.result.data);
										}
									}
								});
							}
						}
					},{
						text : '取 消',
						scope:this,
						handler : function() {
							this.uploadForm.upload_file.setValue('');
							this.hide();
						}
					}]
				}, config);
			Mt.Member.View.BatchUploadImagesWindow.superclass.constructor.call(this, config);
		}
	}),
	/**
	 * 视图：会员列表
	 */
	Grid:Ext.extend(Ext.grid.GridPanel, {
		constructor : function(config) {
			config = Ext.apply({
				/**
				 * 查询条件
				 */
				filter:null,
				region : 'center',
				store : Mt.Member.Store.memberStore,
				sm : this.sm,
				frame : true,trackMouseOver : true,enableColumnMove : true,columnLines : true,
				loadMask : true,stripeRows : true,headerAsText : false,
				defaults : {
					autoScroll : true
				},
				cm : new Ext.grid.ColumnModel({
					defaults:{
						width:120,sortable : true
					},
					columns : [
						this.sm,
                {header : '标识',dataIndex : 'member_id',hidden:true},
                {header : '公司',dataIndex : 'company_name',hidden:true},
                {header : '部门',dataIndex : 'department_name'},
                {header : '职位',dataIndex : 'position_name'},
                {header : '地区',dataIndex : 'area_name'},
                {header : '用户名',dataIndex : 'username'},
                {header : '姓名',dataIndex : 'realname'},
                {header : '员工号',dataIndex : 'code'},
                {header : '电话',dataIndex : 'tel'},
                {header : 'email',dataIndex : 'email'},
                {header : 'qq',dataIndex : 'qq'},
                {header : '微信',dataIndex : 'weixin'},
                {header : '积分',dataIndex : 'point'}
					]
				}),
				tbar : {
					xtype : 'container',layout : 'anchor',height : 27 * 2,style:'font-size:14px',
					defaults : {
						height : 27,anchor : '100%'
					},
					items : [
						new Ext.Toolbar({
							enableOverflow: true,width : 40,
							defaults : {
								xtype : 'textfield',
								listeners : {
								  specialkey : function(field, e) {
										if (e.getKey() == Ext.EventObject.ENTER)this.ownerCt.ownerCt.ownerCt.doSelectMember();
									}
								}
							},
							items : [
                '部门','&nbsp;&nbsp;',{ref: '../mdepartment_id',xtype: 'combo',
                   store:Mt.Member.Store.departmentStoreForCombo,hiddenName : 'department_id',
                   emptyText: '请选择部门',itemSelector: 'div.search-item',
                   loadingText: '查询中...',pageSize:Mt.Member.Config.PageSize,
                   displayField:'department_name',valueField:'department_id',
                   mode: 'remote',editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                   forceSelection: true,triggerAction: 'all',resizable:true,selectOnFocus:true,
                   tpl:new Ext.XTemplate(
                      '<tpl for="."><div class="search-item">',
                      '<h3>{department_name}</h3>',
                      '</div></tpl>'
                   )
                },'&nbsp;&nbsp;',
                '职位','&nbsp;&nbsp;',{ref: '../mposition_id',xtype: 'combo',
                   store:Mt.Member.Store.positionStoreForCombo,hiddenName : 'position_id',
                   emptyText: '请选择职位',itemSelector: 'div.search-item',
                   loadingText: '查询中...',pageSize:Mt.Member.Config.PageSize,
                   displayField:'position_name',valueField:'position_id',
                   mode: 'remote',editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                   forceSelection: true,triggerAction: 'all',resizable:true,selectOnFocus:true,
                   tpl:new Ext.XTemplate(
                      '<tpl for="."><div class="search-item">',
                      '<h3>{position_name}</h3>',
                      '</div></tpl>'
                   )
                },'&nbsp;&nbsp;',
                '地区','&nbsp;&nbsp;',{ref: '../marea_id',xtype: 'combo',
                   store:Mt.Member.Store.areaStoreForCombo,hiddenName : 'area_id',
                   emptyText: '请选择地区',itemSelector: 'div.search-item',
                   loadingText: '查询中...',pageSize:Mt.Member.Config.PageSize,
                   displayField:'area_name',valueField:'area_id',
                   mode: 'remote',editable:true,minChars: 1,autoSelect :true,typeAhead: false,
                   forceSelection: true,triggerAction: 'all',resizable:true,selectOnFocus:true,
                   tpl:new Ext.XTemplate(
                      '<tpl for="."><div class="search-item">',
                      '<h3>{area_name}</h3>',
                      '</div></tpl>'
                   )
                },'&nbsp;&nbsp;',
                '用户名','&nbsp;&nbsp;',{ref: '../musername'},'&nbsp;&nbsp;',
								{
									xtype : 'button',text : '查询',scope: this,
									handler : function() {
										this.doSelectMember();
									}
								},
								{
									xtype : 'button',text : '重置',scope: this,
									handler : function() {
                           // this.topToolbar.mcompany_id.setValue("");
                           this.topToolbar.mdepartment_id.setValue("");
                           this.topToolbar.mposition_id.setValue("");
                           this.topToolbar.marea_id.setValue("");
                           this.topToolbar.musername.setValue("");
										this.filter={};
										this.doSelectMember();
									}
								}]
						}),
						new Ext.Toolbar({
							defaults:{scope: this},
							items : [
								{
									text: '反选',iconCls : 'icon-reverse',
									handler: function(){
										this.onReverseSelect();
									}
								},'-',{
									text : '添加会员',iconCls : 'icon-add',
									handler : function() {
										this.addMember();
									}
								},'-',{
									text : '修改会员',ref: '../../btnUpdate',iconCls : 'icon-edit',disabled : true,
									handler : function() {
										this.updateMember();
									}
								},'-',{
									text : '删除会员', ref: '../../btnRemove',iconCls : 'icon-delete',disabled : true,
									handler : function() {
										this.deleteMember();
									}
								},'-',{
									xtype:'tbsplit',text: '导入', iconCls : 'icon-import',
									handler : function() {
										this.importMember();
									},
									menu: {
										xtype:'menu',plain:true,
										items: [
											{text:'批量导入会员',iconCls : 'icon-import',scope:this,handler:function(){this.importMember()}},
                              {text:'批量导入头像',iconCls : 'icon-import',scope:this,handler:function(){this.batchUploadImages("upload_icon_image_files","头像")}}
										]}
								},'-',{
									text : '导出',iconCls : 'icon-export',
									handler : function() {
										this.exportMember();
									}
								},'-',{
									xtype:'tbsplit',text: '查看会员', ref:'../../tvpView',iconCls : 'icon-updown',
									enableToggle: true, disabled : true,
									handler:function(){this.showMember()},
									menu: {
										xtype:'menu',plain:true,
										items: [
											{text:'上方',group:'mlayout',checked:false,iconCls:'view-top',scope:this,handler:function(){this.onUpDown(1)}},
											{text:'下方',group:'mlayout',checked:true ,iconCls:'view-bottom',scope:this,handler:function(){this.onUpDown(2)}},
											{text:'左侧',group:'mlayout',checked:false,iconCls:'view-left',scope:this,handler:function(){this.onUpDown(3)}},
											{text:'右侧',group:'mlayout',checked:false,iconCls:'view-right',scope:this,handler:function(){this.onUpDown(4)}},
											{text:'隐藏',group:'mlayout',checked:false,iconCls:'view-hide',scope:this,handler:function(){this.hideMember();Mt.Member.Config.View.IsShow=0;}},'-',
											{text: '固定',ref:'mBind',checked: true,scope:this,checkHandler:function(item, checked){this.onBindGrid(item, checked);Mt.Member.Cookie.set('View.IsFix',Mt.Member.Config.View.IsFix);}}
										]}
								},'-']}
					)]
				},
				bbar: new Ext.PagingToolbar({
					pageSize: Mt.Member.Config.PageSize,
					store: Mt.Member.Store.memberStore,
					scope:this,autoShow:true,displayInfo: true,
					displayMsg: '当前显示 {0} - {1}条记录/共 {2}条记录。',
					emptyMsg: "无显示数据",
					listeners:{
						change:function(thisbar,pagedata){
							if (Mt.Member.Viewport){
								if (Mt.Member.Config.View.IsShow==1){
									Mt.Member.View.IsSelectView=1;
								}
								this.ownerCt.hideMember();
								Mt.Member.Config.View.IsShow=0;
							}
						}
					},
					items: [
						{xtype:'label', text: '每页显示'},
						{xtype:'numberfield', value:Mt.Member.Config.PageSize,minValue:1,width:35,
							style:'text-align:center',allowBlank: false,
							listeners:
							{
								change:function(Field, newValue, oldValue){
									var num = parseInt(newValue);
									if (isNaN(num) || !num || num<1)
									{
										num = Mt.Member.Config.PageSize;
										Field.setValue(num);
									}
									this.ownerCt.pageSize= num;
									Mt.Member.Config.PageSize = num;
									this.ownerCt.ownerCt.doSelectMember();
								},
								specialKey :function(field,e){
									if (e.getKey() == Ext.EventObject.ENTER){
										var num = parseInt(field.getValue());
										if (isNaN(num) || !num || num<1)
										{
											num = Mt.Member.Config.PageSize;
										}
										this.ownerCt.pageSize= num;
										Mt.Member.Config.PageSize = num;
										this.ownerCt.ownerCt.doSelectMember();
									}
								}
							}
						},
						{xtype:'label', text: '个'}
					]
				})
			}, config);
			//初始化显示会员列表
			this.doSelectMember();
			Mt.Member.View.Grid.superclass.constructor.call(this, config);
			//创建在Grid里显示的会员信息Tab页
			Mt.Member.View.Running.viewTabs=new Mt.Member.View.MemberView.Tabs();
			this.addListener('rowdblclick', this.onRowDoubleClick);
		},
		/**
		 * 行选择器
		 */
		sm : new Ext.grid.CheckboxSelectionModel({
			//handleMouseDown : Ext.emptyFn,
			listeners : {
				selectionchange:function(sm) {
					// 判断删除和更新按钮是否可以激活
					this.grid.btnRemove.setDisabled(sm.getCount() < 1);
					this.grid.btnUpdate.setDisabled(sm.getCount() != 1);
					this.grid.tvpView.setDisabled(sm.getCount() != 1);
				},
				rowselect: function(sm, rowIndex, record) {
					if (sm.getCount() != 1){
						this.grid.hideMember();
						Mt.Member.Config.View.IsShow=0;
					}else{
						if (Mt.Member.View.IsSelectView==1){
							Mt.Member.View.IsSelectView=0;
							this.grid.showMember();
						}
					}
				},
				rowdeselect: function(sm, rowIndex, record) {
					if (sm.getCount() != 1){
						if (Mt.Member.Config.View.IsShow==1){
							Mt.Member.View.IsSelectView=1;
						}
						this.grid.hideMember();
						Mt.Member.Config.View.IsShow=0;
					}
				}
			}
		}),
		/**
		 * 双击选行
		 */
		onRowDoubleClick:function(grid, rowIndex, e){
			if (!Mt.Member.Config.View.IsShow){
				this.sm.selectRow(rowIndex);
				this.showMember();
				this.tvpView.toggle(true);
			}else{
				this.hideMember();
				Mt.Member.Config.View.IsShow=0;
				this.sm.deselectRow(rowIndex);
				this.tvpView.toggle(false);
			}
		},
		/**
		 * 是否绑定在本窗口上
		 */
		onBindGrid:function(item, checked){
			if (checked){
			  Mt.Member.Config.View.IsFix=1;
			}else{
			  Mt.Member.Config.View.IsFix=0;
			}
			if (this.getSelectionModel().getSelected()==null){
				Mt.Member.Config.View.IsShow=0;
				return ;
			}
			if (Mt.Member.Config.View.IsShow==1){
			  this.hideMember();
			  Mt.Member.Config.View.IsShow=0;
			}
			this.showMember();
		},
		/**
		 * 反选
		 */
		onReverseSelect:function() {
			for (var i = this.getView().getRows().length - 1; i >= 0; i--) {
				if (this.sm.isSelected(i)) {
					this.sm.deselectRow(i);
				}else {
					this.sm.selectRow(i, true);
				}
			}
		},
		/**
		 * 查询符合条件的会员
		 */
		doSelectMember : function() {
			if (this.topToolbar){
           // var mcompany_id = this.topToolbar.mcompany_id.getValue();
           var mdepartment_id = this.topToolbar.mdepartment_id.getValue();
           var mposition_id = this.topToolbar.mposition_id.getValue();
           var marea_id = this.topToolbar.marea_id.getValue();
           var musername = this.topToolbar.musername.getValue();
           this.filter     ={'department_id':mdepartment_id,'position_id':mposition_id,'area_id':marea_id,'username':musername};
			}
			var condition = {'start':0,'limit':Mt.Member.Config.PageSize};
			Ext.apply(condition,this.filter);
			ExtServiceMember.queryPageMember(condition,function(provider, response) {
				if (response.result&&response.result.data) {
					var result        = new Array();
					result['data']     =response.result.data;
					result['totalCount'] =response.result.totalCount;
					Mt.Member.Store.memberStore.loadData(result);
				} else {
					Mt.Member.Store.memberStore.removeAll();
					Ext.Msg.alert('提示', '无符合条件的会员！');
				}
			});
		},
		/**
		 * 显示会员视图
		 * 显示会员的视图相对会员列表Grid的位置
		 * 1:上方,2:下方,0:隐藏。
		 */
		onUpDown:function(viewDirection){
			Mt.Member.Config.View.Direction=viewDirection;
			switch(viewDirection){
				case 1:
					this.ownerCt.north.add(Mt.Member.View.Running.viewTabs);
					break;
				case 2:
					this.ownerCt.south.add(Mt.Member.View.Running.viewTabs);
					break;
				case 3:
					this.ownerCt.west.add(Mt.Member.View.Running.viewTabs);
					break;
				case 4:
					this.ownerCt.east.add(Mt.Member.View.Running.viewTabs);
					break;
			}
			Mt.Member.Cookie.set('View.Direction',Mt.Member.Config.View.Direction);
			if (this.getSelectionModel().getSelected()!=null){
				if ((Mt.Member.Config.View.IsFix==0)&&(Mt.Member.Config.View.IsShow==1)){
					this.showMember();
				}
				Mt.Member.Config.View.IsFix=1;
				Mt.Member.View.Running.memberGrid.tvpView.menu.mBind.setChecked(true,true);
				Mt.Member.Config.View.IsShow=0;
				this.showMember();
			}
		},
		/**
		 * 显示会员
		 */
		showMember : function(){
			if (this.getSelectionModel().getSelected()==null){
				Ext.Msg.alert('提示', '请先选择会员！');
				Mt.Member.Config.View.IsShow=0;
				this.tvpView.toggle(false);
				return ;
			}
			if (Mt.Member.Config.View.IsFix==0){
				if (Mt.Member.View.Running.view_window==null){
					Mt.Member.View.Running.view_window=new Mt.Member.View.MemberView.Window();
				}
				if (Mt.Member.View.Running.view_window.hidden){
					Mt.Member.View.Running.view_window.show();
					Mt.Member.View.Running.view_window.winTabs.hideTabStripItem(Mt.Member.View.Running.view_window.winTabs.tabFix);
					this.updateViewMember();
					this.tvpView.toggle(true);
					Mt.Member.Config.View.IsShow=1;
				}else{
					this.hideMember();
					Mt.Member.Config.View.IsShow=0;
				}
				return;
			}
			switch(Mt.Member.Config.View.Direction){
				case 1:
					if (!this.ownerCt.north.items.contains(Mt.Member.View.Running.viewTabs)){
						this.ownerCt.north.add(Mt.Member.View.Running.viewTabs);
					}
					break;
				case 2:
					if (!this.ownerCt.south.items.contains(Mt.Member.View.Running.viewTabs)){
						this.ownerCt.south.add(Mt.Member.View.Running.viewTabs);
					}
					break;
				case 3:
					if (!this.ownerCt.west.items.contains(Mt.Member.View.Running.viewTabs)){
						this.ownerCt.west.add(Mt.Member.View.Running.viewTabs);
					}
					break;
				case 4:
					if (!this.ownerCt.east.items.contains(Mt.Member.View.Running.viewTabs)){
						this.ownerCt.east.add(Mt.Member.View.Running.viewTabs);
					}
					break;
			}
			this.hideMember();
			if (Mt.Member.Config.View.IsShow==0){
				Mt.Member.View.Running.viewTabs.enableCollapse();
				switch(Mt.Member.Config.View.Direction){
					case 1:
						this.ownerCt.north.show();
						break;
					case 2:
						this.ownerCt.south.show();
						break;
					case 3:
						this.ownerCt.west.show();
						break;
					case 4:
						this.ownerCt.east.show();
						break;
				}
				this.updateViewMember();
				this.tvpView.toggle(true);
				Mt.Member.Config.View.IsShow=1;
			}else{
				Mt.Member.Config.View.IsShow=0;
			}
			this.ownerCt.doLayout();
		},
		/**
		 * 隐藏会员
		 */
		hideMember : function(){
			this.ownerCt.north.hide();
			this.ownerCt.south.hide();
			this.ownerCt.west.hide();
			this.ownerCt.east.hide();
			if (Mt.Member.View.Running.view_window!=null){
				Mt.Member.View.Running.view_window.hide();
			}
			this.tvpView.toggle(false);
			this.ownerCt.doLayout();
		},
		/**
		 * 更新当前会员显示信息
		 */
		updateViewMember : function() {

			if (Mt.Member.View.Running.view_window!=null){
				Mt.Member.View.Running.view_window.winTabs.tabMemberDetail.update(this.getSelectionModel().getSelected().data);
			}
			Mt.Member.View.Running.viewTabs.tabMemberDetail.update(this.getSelectionModel().getSelected().data);
		},
		/**
		 * 新建会员
		 */
		addMember : function() {
			if (Mt.Member.View.Running.edit_window==null){
				Mt.Member.View.Running.edit_window=new Mt.Member.View.EditWindow();
			}
			Mt.Member.View.Running.edit_window.resetBtn.setVisible(false);
			Mt.Member.View.Running.edit_window.saveBtn.setText('保 存');
			Mt.Member.View.Running.edit_window.setTitle('添加会员');
			Mt.Member.View.Running.edit_window.savetype=0;
			Mt.Member.View.Running.edit_window.member_id.setValue("");
        Mt.Member.View.Running.edit_window.icon_imageUpload.setValue("");
        var passwordObj=Mt.Member.View.Running.edit_window.password;
        passwordObj.allowBlank=false;
        if (passwordObj.getEl()) passwordObj.getEl().dom.parentNode.previousSibling.innerHTML ="密码(<font color=red>*</font>)";

			Mt.Member.View.Running.edit_window.show();
			Mt.Member.View.Running.edit_window.maximize();
		},
		/**
		 * 编辑会员时先获得选中的会员信息
		 */
		updateMember : function() {
			if (Mt.Member.View.Running.edit_window==null){
				Mt.Member.View.Running.edit_window=new Mt.Member.View.EditWindow();
			}
			Mt.Member.View.Running.edit_window.saveBtn.setText('修 改');
			Mt.Member.View.Running.edit_window.resetBtn.setVisible(true);
			Mt.Member.View.Running.edit_window.setTitle('修改会员');
			Mt.Member.View.Running.edit_window.editForm.form.loadRecord(this.getSelectionModel().getSelected());
			Mt.Member.View.Running.edit_window.savetype=1;
        Mt.Member.View.Running.edit_window.icon_imageUpload.setValue(Mt.Member.View.Running.edit_window.icon_image.getValue());

			Mt.Member.View.Running.edit_window.show();

        var passwordObj=Mt.Member.View.Running.edit_window.password;
        passwordObj.allowBlank=true;
        if (passwordObj.getEl())passwordObj.getEl().dom.parentNode.previousSibling.innerHTML ="密码";
        Mt.Member.View.Running.edit_window.password_old.setValue(Mt.Member.View.Running.edit_window.password.getValue());
        Mt.Member.View.Running.edit_window.password.setValue("");

			Mt.Member.View.Running.edit_window.maximize();
		},
		/**
		 * 删除会员
		 */
		deleteMember : function() {
			Ext.Msg.confirm('提示', '确实要删除所选的会员吗?', this.confirmDeleteMember,this);
		},
		/**
		 * 确认删除会员
		 */
		confirmDeleteMember : function(btn) {
			if (btn == 'yes') {
				var del_member_ids ="";
				var selectedRows   = this.getSelectionModel().getSelections();
				for ( var flag = 0; flag < selectedRows.length; flag++) {
					del_member_ids=del_member_ids+selectedRows[flag].data.member_id+",";
				}
				ExtServiceMember.deleteByIds(del_member_ids);
				this.doSelectMember();
				Ext.Msg.alert("提示", "删除成功！");
			}
		},
		/**
		 * 导出会员
		 */
		exportMember : function() {
			ExtServiceMember.exportMember(this.filter,function(provider, response) {
				if (response.result.data) {
					window.open(response.result.data);
				}
			});
		},
		/**
		 * 导入会员
		 */
		importMember : function() {
			if (Mt.Member.View.current_uploadWindow==null){
				Mt.Member.View.current_uploadWindow=new Mt.Member.View.UploadWindow();
			}
			Mt.Member.View.current_uploadWindow.show();
		},
		/**
		 * 批量上传商品图片
		 */
		batchUploadImages:function(inputname,title){
			if (Mt.Member.View.Running.batchUploadImagesWindow==null){
           Mt.Member.View.Running.batchUploadImagesWindow=new Mt.Member.View.BatchUploadImagesWindow();
        }

			Mt.Member.View.Running.batchUploadImagesWindow.setTitle("批量上传"+title);
			Mt.Member.View.Running.batchUploadImagesWindow.uploadForm.upload_file.name=inputname;
			Mt.Member.View.Running.batchUploadImagesWindow.show();
		}
	}),
	/**
	 * 核心内容区
	 */
	Panel:Ext.extend(Ext.form.FormPanel,{
		constructor : function(config) {
			Mt.Member.View.Running.memberGrid=new Mt.Member.View.Grid();
			if (Mt.Member.Config.View.IsFix==0){
				Mt.Member.View.Running.memberGrid.tvpView.menu.mBind.setChecked(false,true);
			}
			config = Ext.apply({
				region : 'center',layout : 'fit', frame:true,
				items: {
					layout:'border',
					items:[
						Mt.Member.View.Running.memberGrid,
						{region:'north',ref:'north',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true},
						{region:'south',ref:'south',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true,items:[Mt.Member.View.Running.viewTabs]},
						{region:'west',ref:'west',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true},
						{region:'east',ref:'east',layout:'fit',collapseMode : 'mini',border:false,split: true,hidden:true}
					]
				}
			}, config);
			Mt.Member.View.Panel.superclass.constructor.call(this, config);
		}
	}),
	/**
	 * 当前运行的可视化对象
	 */
	Running:{
		/**
		 * 当前会员Grid对象
		 */
		memberGrid:null,

		/**
		 * 显示会员信息及关联信息列表的Tab页
		 */
		viewTabs:null,
		/**
		 * 当前创建的编辑窗口
		 */
		edit_window:null,
		/**
		 * 当前的显示窗口
		 */
		view_window:null
	}
};
/**
 * Controller:主程序
 */
Ext.onReady(function(){
	Ext.QuickTips.init();
	Ext.state.Manager.setProvider(Mt.Member.Cookie);
	Ext.Direct.addProvider(Ext.app.REMOTING_API);
	Mt.Member.Init();
	/**
	 * 会员数据模型获取数据Direct调用
	 */
	Mt.Member.Store.memberStore.proxy=new Ext.data.DirectProxy({
		api: {read:ExtServiceMember.queryPageMember}
	});
	/**
	 * 会员页面布局
	 */
	Mt.Member.Viewport = new Ext.Viewport({
		layout : 'border',
		items : [new Mt.Member.View.Panel()]
	});
	Mt.Member.Viewport.doLayout();
	setTimeout(function(){
		Ext.get('loading').remove();
		Ext.get('loading-mask').fadeOut({
			remove:true
		});
	}, 250);
});